import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { DNavBar, DModal } from '@/components'
import DHeader from './component/header'
import DContent from './component/content'
import DList from './component/list'
import DFooter from './component/footer'
import classNames from 'classnames'
import http from '@/api'
import sdk from '@/common/sdk'
import dayjs from 'dayjs'
import './itemdetail.scss'

class Ddrawdetail extends Component {

  constructor(props) {
    super(props)
    this.state = {
      bgImages: require('../assets/bgImages.png'),
      title: "退款详情",
      info: {
        // "businessOrderNo": "业务订单号",
        // "createBy": "申请人",
        // "createSendTime": "发起退款时间",
        // "createTime": "提交时间",
        // "endSendTime": "退款成功时间",
        // "modifyBy": "修改人",
        // "modifyTime": "修改时间",
        // "recStatus": "逻辑删除",
        // "refundAmount": "退款金额",
        // "refundStatus": "退款状态",
        // "refundType": "退款类型",
        // "remark": "备注",
        // "sendBackWay": "退回方式",
        // "sendBankNumber": "退回银行卡号",
        // "sendBankPersion": "退回银行卡账号持卡人",
        // "theLatest": "是否最新",
        // "toId": "交易订单编号",
        // "trId": "退款单号",
        // "transactionOrderNumber": "交易单号"
      },
      headerobj: {
        itemtime: {
          isShowDay: false,
          isShowHour: false,
          day: 0,
          hours: 0,
          minutes: 0,
          seconds: 0
        },
        isdraw: true
      },
      isShow: false,
      item: {},
      crmodal: '',
      modal1: '',
      id: '',
      firstList: {
        info: [
          {
            label: "业务订单：",
            value: ""
          },
          {
            label: "买家名称：",
            value: ""
          },
          {
            label: "买家联系人：",
            value: ""
          },
          {
            label: "买家联系方式：",
            value: ""
          }
        ]
      },
      status: '',
      secondList: {
        title: "车辆信息",
        info: [
          {
            label: "交易车型：",
            value: ""
          },
          {
            label: "车源类型：",
            value: ""
          },
          {
            label: "指导价：",
            value: ""
          },
          {
            label: "外观颜色：",
            value: ""
          },
          {
            label: "内饰颜色",
            value: ""
          },
          {
            label: "上牌地点：",
            value: ""
          },
          {
            label: "寻车状态：",
            value: ""
          },
          {
            label: "备注：",
            value: ""
          },
        ]
      },
      threeList: {
        title: "交易信息",
        info: [
          {
            label: "成交数量",
            value: ""
          },
          {
            label: "成交总价",
            value: ""
          },
          {
            label: "订金金额",
            value: ""
          }
        ]
      },
      dlist: {
        list: [
          {
            title: '合同凭证'
          }
        ]
      }


    }
  }

  componentWillMount() {
    let { id, status } = this.$router.params
    this.setState({
      status,
      id,
      headerobj: {
        title: ''
      }
    })
    this.getDetailList(id)
  }

  componentDidShow() {
    sdk.setTitleInfo(this.state.title)
  }
  fixedRes(res = {}) {
    // res = this.state.info
    let { firstList, secondList, threeList } = this.state
    // 单位配对
    function getPrice(i) {
      return {
        $0: '台',
        $1: '万元',
        $2: '元'
      }[`$${i}`]
    }

    let _firstList = ['businessOrderNo', 'comName', 'creator', 'creatorContact']
    firstList.info.map((item, i) => {
      item.value = (res[_firstList[i]] || '--')
    })

    let _secondList = ['orCarModel', 'orCarSourceType', 'orCarGuiPrice', 'orCarOutColor', 'orCarInColor', 'orCarEmissionStd',
      'orCarSourceType', 'orCarGuiPrice', 'remark',
    ]
    secondList.info.map((item, i) => {
      item.value = (res[_secondList[i]] || '--') + (i === 2 ? getPrice(1) : '')
    })

    let _threeList = ['orCount', 'orTotalPrice', 'refundAmount']
    threeList.info.map((item, i) => {
      item.value = (res[_threeList[i]] || '--') + getPrice(i)
    })

    //根据订单状态计算倒计时
    let orStatus = this.$router.params.status
    let times = ''
    if (orStatus === '21') {
      let createTime = dayjs(res.createTime).add(30, 'minute')
      times = createTime.diff(dayjs(), 'day', 'true')
    } else if (orStatus === '32') {
      let createTime = dayjs(res.updateTime).add(3, 'day')
      times = createTime.diff(dayjs(), 'day', 'true')
    } else {
      times = 0
    }
    this.setState({
      firstList,
      secondList,
      threeList,
      item: res,
      headerobj: {
        ...this.state.headerobj,
        account: res.transactionOrderNumber,
        text: '退款原因:【卖家确认退款】',
        tiptext: '',
        title: '退款',
        itemtime: {
          // isShowDay: false,
          // isShowHour: false,
          // day: times,
          // hours: 0,
          // minutes: 30,
          // seconds: 0
        }
      }
    })
  }
  getDetailList(id) {
    http.tradingRefund({}, id).then(res => {
      if (!res) {
        return
      }

      let orNo = res.businessOrderNo
      // 寻车列表没有数据则请求物流列表接口
      http.getTransCar({ limit: 10, page: 1, orNo, sign: 0 }).then(data => {
        if (data.list.length === 0) {
          http.getListTrans({ limit: 10, page: 1, orNo }).then(data => {
            var list = { ...res, ...data.list[0] }
            this.fixedRes({ ...res, ...data.list[0] })
          })
        } else {
          var list = { ...res, ...data.list[0] }
          this.fixedRes({ ...res, ...data.list[0] })
        }
      })

    })
  }
  getStatus(status) {
    return {
      $21: `待接单`,
      $31: `待上传`,
      $32: `待买家确认`,
      $33: `待核实`,
      $41: `交易成功`,
      $42: `已拒接`,
      $43: `已撤回`,
      $44: `已超时`,
      $45: `交易异常`
    }[`$${status}`]
  }
  getPlatformTxt(orstatu) {
    return {
      $21: '系统将自动拒绝接单',
      $32: '将自动确认',
      // $33: '将自动确认',
    }[`$${orstatu}`]
  }
  getText(orstatu) {
    return {
      $21: '请确认消息以及是否接单',
      $31: '请在交易完成后上传相关合同及凭证',
      $32: '买家正在核实订单，请耐心等候',
      $33: `平台将在<text style='font-size:20px;font-weight:bold;color:#FFAE00'>5</text>日内核实订单，逾时将自动确认`,
      $41: '亲，恭喜你成功完成一笔订单！企业管理员可提现订金',
      $42: '该订单已拒接',
      $44: '该订单已超时',
      $43: '很遗憾，买家已取消订单',
      $45: '您的订单交易异常，平台客服已介入并终止'
    }[`$${orstatu}`]
  }

  hanleFirst(status) {
    let isShow = true
    this.setState({
      isShow,
      crmodal: status,
      modal1: '您确认拒绝接受订单吗？'
    })
  }

  refuseSaleOrder(orderId) {
    http.refuseSaleOrder2({ orderId: orderId }).then((res) => {
      if (!res) {
        return
      }
      Taro.redirectTo({
        url: `/pages/itemdetail/saledetail?id=${orderId}&status=42`
      })
    })
  }

  handleLast(status) {
    if (this.state.headerobj.itemtime.day <= 0) {
      return Taro.showToast({
        title: '订单超时,系统已经自动拒绝接单',
        icon: "none"
      })
    }
    let isShow = true
    this.setState({
      isShow,
      crmodal: status,
      modal1: '您确认接受订单吗？'
    })
  }

  confirmSaleOrder(orderId) {
    http.acceptSaleOrder({ orderId: orderId }).then((res) => {
      if (!res) {
        return
      }
      Taro.redirectTo({
        url: `/pages/itemdetail/saledetail?id=${orderId}&status=31`
      })
    })
  }

  onClose() {
    this.setState({
      isShow: false
    })
  }

  onLastHandle() {
    let { crmodal, item } = this.state
    this.onClose()
    if (crmodal === '1') {
      this.refuseSaleOrder(item.id)

    } else if (crmodal === '2') {
      this.confirmSaleOrder(item.id)
    }
  }

  handleContact() {
    let { id } = this.state
    Taro.navigateTo({
      url: `/pages/contractproof/contractproof?id=${id}&status=1`
    })
  }
  hanleFirst1() {
    const { id } = this.state
    http.clcgTemplate(id).then((res, urls) => {
      // 下载合同接口
      const a = document.createElement('a');
      const url = urls;
      const filename = '车辆采购合同下载.zip';
      a.href = url;
      a.download = filename;
      a.click();
    })
  }
  handleLast1() {
    const { id } = this.state
    Taro.redirectTo({
      url: `/pages/caruploadinfo/caruploadinfo?id=${id}`
    })
  }
  render() {
    const {
      bgImages,
      title,
      firstList,
      secondList,
      threeList,
      headerobj,
      isShow,
      status,
      dlist,
      modal1
    } = this.state

    return (
      <View className='b_itemdetail'>
        <Image src={bgImages} className={classNames('b_itemdetail__imagebs', process.env.NODE_ENV === 'development' ? '' : 'b_itemdetail__NODEimg')}></Image>
        <DNavBar title={title} className='b_itemdetail__nav'></DNavBar>
        <View className='b_itemdetail__box'>
          <View className='b_itemdetail__content'>
            <DHeader {...headerobj}></DHeader>

            <DContent {...firstList}></DContent>
            <DContent {...secondList}></DContent>
            <DContent {...threeList}></DContent>

            {status === '31' &&
              <DFooter onFirstClick={this.hanleFirst1.bind(this)} secondText='上传资料' onSeconClick={this.handleLast1.bind(this)}></DFooter>
            }
          </View>
        </View>
        <DModal
          isShow={isShow}
          title='提示'
          text={modal1}
          firstbtn='取消'
          lastbtn='确认'
          onFirst={this.onClose.bind(this)}
          onCancel={this.onClose.bind(this)}
          onLast={this.onLastHandle.bind(this)}
        ></DModal>
      </View>
    )
  }

}


export default Ddrawdetail
